# coding: utf-8
import random
from subprocess import Popen
from celery_app import app
from lib.youtobe.main import run_crawler
from settings import START_CONTAINER, redis_instance


@app.task
def you_to_be(tag_list, create_time, update_time, craw_number,
              email_address_list, error_log, loop_crawl,
              upload_file_name, log_file_name):
    # 执行任务
    run_crawler(tag_list, create_time, update_time, craw_number,
                email_address_list, error_log, loop_crawl,
                upload_file_name, log_file_name)


@app.task
def open_chrome():
    while True:
        port = random.choices(range(8888, 55555))
        port = str(port[0])
        if redis_instance.get(port):
            continue
        redis_instance.set(port, "1", ex=(60 * 30))
        break
    cmd = START_CONTAINER.format(port=port)
    print(f"start container command: {cmd}")
    p = Popen(cmd, shell=True)
    out, err = p.communicate()
    return out
